<?php
/**
 * Remove A Partner from a Medical Center
 *
 * @author Xavier VILAIN
 * @package MedicalStudy\MedicalCenter\Partner
 * @license
 */
use Nawa\Customer;
use Nawa\MedicalStudy\MedicalCenter\Partner;
use Nawa\MedicalStudy\MedicalCenter;
use Nawa\Messages;
use Fox\Message;
$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$customerid = $xview->val('customerid');
$monitoringid = $xview->val('monitoringid');
try {
	$ms = $xview->component('medicalstudies','object',array('msid' => $msid)); 
	$medicalCenterPartner = $ms->findMedicalCentersPartners($ms->getInlineId().':'.$mcid);
	if(!empty($monitoringid)) {
		
		$monitoring = $medicalCenterPartner->findMonitorings($medicalCenterPartner->getInlineId().':'.$monitoringid);
		$monitoringPartner = $monitoring->findPartners($monitoring->getInlineId().':'.$customerid);
		if($monitoringPartner->exists())
		{
			if($monitoring->countPartners() == 1) {
				Message::Error(Msg(Messages::BUNDLE,Messages::ERR_PARTNER_UNASSIGN_FROM_MONITORING,Customer::fullName($monitoringPartner->customerid)));
			} else {
				$monitoringPartner->delete();
				Message::Success(Msg(Messages::BUNDLE,Messages::MSG_PARTNER_UNASSIGN_FROM_MONITORING,$monitoring->label()));
			}
		}
	}
	elseif(!empty($customerid)) {
		$medicalCenter = \Fox\Dao::load(\Nawa\MedicalCenter::className(),$mcid);
		$mcPartner = $medicalCenterPartner->findPartners($medicalCenterPartner->getInlineId().':'.$customerid);
		if($mcPartner->exists())
		{
			$mcPartner->delete();
			Message::Success(Msg(Messages::BUNDLE,Messages::MSG_PARTNER_UNASSIGN_FROM_MC,$medicalCenter->name1));
		}
	}
}
catch (Fox\Object\Exception\Save $e)
{
	Fox\Message::Error($e);
}
catch (Fox\Object\Exception\NotExist $e)
{
	Fox\Message::Error($e);
}
echo Xview::instance()->messages(true,true);